// app.js
App({
  onLaunch() {
    // 展示本地存储能力
    // const logs = wx.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)

    // 登录
    // wx.login({
    //   success: res => {
    //     // 发送 res.code 到后台换取 openId, sessionKey, unionId
    //   }
    // })

  },

  watch:function(method) {
    var obj = this.globalData
    Object.defineProperty(obj,"ecg",{
      configurable:true,
      enumerable:true,
      set:function (value) {
        console.log('监听数据已修改')
        this._ecg = value
        method(value);
      },
      get:function () {
        return this._ecg
      }
    })
  },

  globalData: {
    userInfo: null,
    ecg:{
      connected:false,
      battery: "100",
      deviceName: "",
    },
    ecg_hw:"",
    ecg_fw:"",
    deviceId:"",
    sensor_connected: true,
    decryptKey: "",
    incompleteAnaData:[], //未完成解析的数据

  },
  //打开蓝牙模式 扫描设备的基础
  openBleAdapter(callback){
    wx.openBluetoothAdapter({
      mode: 'central',
      success: (res) => {
        callback(res)
      },
      fail: (res) => {
        callback(res)
      },
      complete: (res) => {},
    })
  },
  //关闭蓝牙适配器  在退出小程序或者不需要蓝牙连接时关闭
  closeBleAdapter(){
    wx.closeBluetoothAdapter({
      success: (res) => {},
    })
  },
  startScan(callback){
    console.log('app.js里面的开始扫描')
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        // console.log('startBluetoothDevicesDiscovery success',res)
        callback(res)
      },
      fail: (res) => {
        // console.log('startBluetoothDevicesDiscovery failed',res)
        callback(res)
      },
      complete: (res) => {},
    })
  },
  stopScan(callback){
    wx.stopBluetoothDevicesDiscovery({
      success: (res) => {
        callback(res)
      },
    })
  },
  connectSensor(deviceId,connectTimeOut,callback){
    var that = this
    wx.createBLEConnection({
      deviceId: deviceId,
      timeout:connectTimeOut,
      success(res) {
        callback('连接成功')
        that.discoveryBleServices(deviceId,callback)
      },
      fail(res){
        callback('连接失败')
      },
      complete:(res) =>{}
    })
  },
  disconnectECG(sensorName){
    wx.closeBLEConnection({
      deviceId:sensorName
    })
  },
  //扫描BLE的services
  discoveryBleServices(deviceId,callback){
    var that = this
    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success:(res) => {
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            let seviceUUID = res.services[i].uuid
            console.log('服务的UUID:',seviceUUID)
            that.discoveryBleCharacteristics(deviceId, seviceUUID,callback)
          }
        }
      }
    })
  },
  discoveryBleCharacteristics(deviceId, seviceUUID, callback){
    var that = this
    wx.getBLEDeviceCharacteristics({
      deviceId: deviceId,
      serviceId: seviceUUID,
      success:(res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          const item = res.characteristics[i]
          if (item.properties.read) {
            callback('获取读的特征值UUID')
            wx.readBLECharacteristicValue({
              deviceId:deviceId,
              serviceId: seviceUUID,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            callback('获取写的特征值UUID')
            // that.setData({
            //   canWrite: true
            // })
            that.globalData._deviceId = deviceId
            that.globalData._serviceId = seviceUUID
            that.globalData._characteristicId = item.uuid
            // that.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            callback('获取通知的特征值UUID')
            wx.notifyBLECharacteristicValueChange({
              deviceId:deviceId,
              serviceId:seviceUUID,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        // console.error('getBLEDeviceCharacteristics', res)
        console.log('Characteristics 失败')
      }
    })
  },
  //忘蓝牙设备写数据
  writeBLECharacteristicValue(dataBuffer) {
    var that = this
    // console.log('that deviceId:',that.globalData._deviceId)
    // console.log('that serviceId:',that.globalData._serviceId)
    // console.log('that characteristicId:',that.globalData._characteristicId)
    console.log('write:',dataBuffer)
    wx.writeBLECharacteristicValue({
      deviceId: that.globalData._deviceId,
      serviceId: that.globalData._serviceId,
      characteristicId: that.globalData._characteristicId,
      value: dataBuffer,
      success() {
        console.log('writeBLECharacteristicValue: 成功')
      },
      fail() {
        console.log('writeBLECharacteristicValue: 失败')
      },
      complete() {
        console.log('writeBLECharacteristicValue: 结束')
      }
    })
  },
})
